//
//	ReaderDemoController.m
//	Reader v2.0.0
//
//	Created by Julius Oklamcak on 2011-07-01.
//	Copyright © 2011 Julius Oklamcak. All rights reserved.
//
//	This work is being made available under a Creative Commons Attribution license:
//		«http://creativecommons.org/licenses/by/3.0/»
//	You are free to use this work and any derivatives of this work in personal and/or
//	commercial products and projects as long as the above copyright is maintained and
//	the original author is attributed.
//

#import "ReaderPDFController.h"
#import "AppDelegate.h"
@implementation ReaderPDFController
@synthesize AppleDeglate;

#pragma mark Constants

 

#define DEMO_VIEW_CONTROLLER_PUSH FALSE

#pragma mark Properties

//@synthesize ;

#pragma mark UIViewController methods

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

	if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]))
	{
		// Custom initialization
	}

	return self;
}
*/

/*
- (void)loadView
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

	// Implement loadView to create a view hierarchy programmatically, without using a nib.
}
*/
-(id)initPdfFilename:(NSString *)name {
	self= [super init];
	if (self ) {
		 pdfFilename=name;
	}
	return self;	 	
}



-(void)get_pdfFilename:(NSString *)filename{
    pdfFilename=filename;

}


- (void)viewDidLoad
{
   [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
    haveDownload=NO  ;  
    
    
#ifdef DEBUGX
	NSLog(@"%s %@", __FUNCTION__, NSStringFromCGRect(self.view.bounds));
#endif

	[super viewDidLoad];

	self.view.backgroundColor = [UIColor clearColor]; // Clear background color
 
	self.title = NSLocalizedString(@"Instructions", @"Instructions")  ; // Show app version

	CGSize viewSize = self.view.bounds.size;

	CGRect labelRect = CGRectMake(0.0f, 0.0f, 200.0f, 32.0f);

    tapLabel = [[UILabel alloc] initWithFrame:labelRect];

	 
	tapLabel.textColor = [UIColor whiteColor];
	tapLabel.textAlignment = UITextAlignmentCenter;
	tapLabel.backgroundColor = [UIColor clearColor];
	tapLabel.font = [UIFont systemFontOfSize:24.0f];
	tapLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
	tapLabel.autoresizingMask |= UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
	tapLabel.center = CGPointMake(viewSize.width / 2.0f, viewSize.height / 2.0f);

    tapLabel.text = NSLocalizedString(@"Downloading...",@"下載中...");    
	[self.view addSubview:tapLabel]; [tapLabel release];

       
    
    
	UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
	//singleTap.numberOfTouchesRequired = 1; singleTap.numberOfTapsRequired = 1; //singleTap.delegate = self;
	[self.view addGestureRecognizer:singleTap]; [singleTap release];
    
    
   
   
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
#ifdef DEBUGX
	NSLog(@"%s %@", __FUNCTION__, NSStringFromCGRect(self.view.bounds));
#endif

	[super viewWillAppear:animated];

#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)

	[self.navigationController setNavigationBarHidden:NO animated:animated];

#endif
}

- (void)viewDidAppear:(BOOL)animated
{
    if (haveDownload==NO) {
        
        //顯示之後開始下載資料
        //說明書下載網址
        NSString *urls;
        urls = [NSString stringWithFormat:@"http://www.xxtradexx.com/help_instruction/"];
        urls=[urls stringByAppendingString:pdfFilename];   
        
        //下載資料儲存位置與檔名合在一起-Documents
        //路徑
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *resourceDocPath = [[paths objectAtIndex:0] retain];        
         NSLog(@"resourceDocPath=%@",resourceDocPath);
       // NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
      
       // NSLog(@"resourceDocPath=%@",resourceDocPath);
        
        NSString *filePath = [resourceDocPath stringByAppendingPathComponent:pdfFilename];

        //刪除ＰＤＦ記錄檔plist(此檔案是用來記錄過去閱讀記錄如果不刪除則就算下載新的檔案版本也無法覆蓋)
        NSString *plistFilename;
        //修改副檔名
        plistFilename=[pdfFilename stringByReplacingOccurrencesOfString:@"pdf" withString:@"plist"];
        NSString *filepath_plist=[resourceDocPath stringByAppendingPathComponent:plistFilename];
        NSFileManager  *fileManager = [NSFileManager defaultManager];
        
        if ([fileManager fileExistsAtPath:filepath_plist]) {
            NSLog(@"yes");
            NSError *error;
            BOOL success;            
            success=[fileManager removeItemAtPath:filepath_plist error:&error];            
            if (success) {
                NSLog(@"delete plist");
            }
            
        }
        
        
        NSLog(@"filepath_plist=%@",filepath_plist);
        
        //下載資料
        NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: urls ]];
        
                
        //將下載資料儲存成檔案
        [pdfData writeToFile:filePath atomically:YES];     
        
        [pdfData release];
        //[filePath release];
        [resourceDocPath release];
        
        tapLabel.text = NSLocalizedString(@"Tap to read", @"點選 閱讀");     
        
        [self show_pdf];        
        //[super viewDidAppear:animated];        
        haveDownload=YES;  
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;         
        
    }
  
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
#ifdef DEBUGX
	NSLog(@"%s %@", __FUNCTION__, NSStringFromCGRect(self.view.bounds));
#endif

	[super viewWillDisappear:animated];

#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)

	[self.navigationController setNavigationBarHidden:YES animated:animated];

#endif
}

- (void)viewDidDisappear:(BOOL)animated
{
#ifdef DEBUGX
	NSLog(@"%s %@", __FUNCTION__, NSStringFromCGRect(self.view.bounds));
#endif

	[super viewDidDisappear:animated];
}

- (void)viewDidUnload
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

	[super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
#ifdef DEBUGX
	NSLog(@"%s (%d)", __FUNCTION__, interfaceOrientation);
#endif

	return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
#ifdef DEBUGX
	NSLog(@"%s %@ (%d)", __FUNCTION__, NSStringFromCGRect(self.view.bounds), toInterfaceOrientation);
#endif
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
#ifdef DEBUGX
	NSLog(@"%s %@ (%d)", __FUNCTION__, NSStringFromCGRect(self.view.bounds), interfaceOrientation);
#endif
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
#ifdef DEBUGX
	NSLog(@"%s %@ (%d to %d)", __FUNCTION__, NSStringFromCGRect(self.view.bounds), fromInterfaceOrientation, self.interfaceOrientation);
#endif

	//if (fromInterfaceOrientation == self.interfaceOrientation) return;
}

- (void)didReceiveMemoryWarning
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

	[super didReceiveMemoryWarning];
}

- (void)dealloc
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif
    [tapLabel release];
	[super dealloc];
}

#pragma mark UIGestureRecognizer methods

-(void)show_pdf{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif
    
	ReaderDocument *document = [ReaderDocument unarchiveFromFileName:pdfFilename];
    
	if (document == nil) // Create a brand new ReaderDocument object the first time we run
	{
		//路徑
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *dir = [paths objectAtIndex:0];
        //路徑+名稱
        
        
        NSString *filePath = [[[NSString alloc] initWithString:[dir stringByAppendingPathComponent:pdfFilename]] autorelease];
        
        
        
        //NSString *filePath = [[NSBundle mainBundle] pathForResource:pdfFilename ofType:nil];
        
		document = [[[ReaderDocument alloc] initWithFilePath:filePath password:nil] autorelease];
	}
    
	ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
    
	readerViewController.delegate = self; // Set the ReaderViewController delegate to self
    
#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
    
	[self.navigationController pushViewController:readerViewController animated:YES];
    
#else // present modal view controller
    
	readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
	readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    
	[self presentModalViewController:readerViewController animated:YES];
    
#endif
    
	[readerViewController release]; // Release the ReaderViewController
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
        
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
            //垂直
            if( [(AppDelegate * )AppleDeglate Master_popController]!=nil ){
                [[(AppDelegate * )AppleDeglate Master_popController]  dismissPopoverAnimated:YES];       
                
            }    
            
            
            
        }
        else{
            //水平
            //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
            [self dismissModalViewControllerAnimated:YES];                         
        }
        
        
    }
    
    
    

}



- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

	ReaderDocument *document = [ReaderDocument unarchiveFromFileName:pdfFilename];

	if (document == nil) // Create a brand new ReaderDocument object the first time we run
	{
		//路徑
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *dir = [paths objectAtIndex:0];
        //路徑+名稱
        
        
        NSString *filePath = [[[NSString alloc] initWithString:[dir stringByAppendingPathComponent:pdfFilename]] autorelease];
                
        
        
        //NSString *filePath = [[NSBundle mainBundle] pathForResource:pdfFilename ofType:nil];

		document = [[[ReaderDocument alloc] initWithFilePath:filePath password:nil] autorelease];
	}

	ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];

	readerViewController.delegate = self; // Set the ReaderViewController delegate to self

#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)

	[self.navigationController pushViewController:readerViewController animated:YES];

#else // present modal view controller

	readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
	readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;

	[self presentModalViewController:readerViewController animated:YES];

#endif

	[readerViewController release]; // Release the ReaderViewController
     
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
        
        if ( [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString:@"UIInterfaceOrientationPortrait 垂直"] || [[(AppDelegate * )AppleDeglate interfaceOrientation_ipad] isEqualToString: @"UIInterfaceOrientationPortraitUpsideDown 垂直"] ) {
            //垂直
            if( [(AppDelegate * )AppleDeglate Master_popController]!=nil ){
                [[(AppDelegate * )AppleDeglate Master_popController]  dismissPopoverAnimated:YES];       
                
            }    
            
            
            
        }
        else{
            //水平
            //[delegate_UIPopoverController dismissPopoverAnimated:YES]; 
            [self dismissModalViewControllerAnimated:YES];                         
        }
        
        
    }
   
    
    
    
}

#pragma mark ReaderViewControllerDelegate methods

- (void)dismissReaderViewController:(ReaderViewController *)viewController
{
#ifdef DEBUGX
	NSLog(@"%s", __FUNCTION__);
#endif

#if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)

	[self.navigationController popViewControllerAnimated:YES];

#else // dismiss modal view controller

	[self dismissModalViewControllerAnimated:YES];

#endif
}

@end
